﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace WSick.Client.Extensions
{
    public partial class Command
    {
        public static readonly DependencyProperty SelectionChangedCommandProperty = DependencyProperty.RegisterAttached(
            "SelectionChangedCommand", typeof(ICommand), typeof(Command), new PropertyMetadata(OnSelectionChangedCommandPropertyChanged));

        public static readonly DependencyProperty SelectionChangedCommandParameterProperty = DependencyProperty.RegisterAttached(
            "SelectionChangedCommandParameter", typeof(ICommand), typeof(Command), new PropertyMetadata(null));

        public static ICommand GetSelectionChangedCommand(object d)
        {
            if (d is DependencyObject)
                return (ICommand)(d as DependencyObject).GetValue(SelectionChangedCommandProperty);
            return null;
        }

        public static void SetSelectionChangedCommand(object d, ICommand cmd)
        {
            if (d is DependencyObject)
                (d as DependencyObject).SetValue(SelectionChangedCommandProperty, cmd);
        }

        public static object GetSelectionChangedCommandParameter(object d)
        {
            if (d is DependencyObject)
                return (d as DependencyObject).GetValue(SelectionChangedCommandParameterProperty);
            return null;
        }

        private static void OnSelectionChangedCommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is Selector)
            {
                if (e.OldValue == null && e.NewValue != null)
                {
                    (d as Selector).SelectionChanged += CommandHelper_SelectionChanged;
                }
                else if (e.OldValue != null && e.NewValue == null)
                {
                    (d as Selector).SelectionChanged -= CommandHelper_SelectionChanged;
                }
            }
        }

        public static void CommandHelper_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is Selector)
            {
                ICommand cmd = GetSelectionChangedCommand(sender);
                object param = GetSelectionChangedCommandParameter(sender);
                if (cmd.CanExecute(param))
                    cmd.Execute(param);
            }
        }
    }
}
